package com.lxy.interceptor;

import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

public class TokenInterceptor implements HandlerInterceptor {


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        //获取token
        String token = request.getHeader("token");
        if (null == token){
            //用户没有token 无权访问
            fail(response,"没有token,无权访问");
        }
        return HandlerInterceptor.super.preHandle(request, response, handler);
    }

    void fail(HttpServletResponse response, String msg) {
        //设置中文
        response.setContentType("application/json;charset=utf-8");
        //获取输出流  jdk8  资源 自动释放
        try (PrintWriter pw = response.getWriter();) {
            pw.write("{\"code\":0,\"msg\":\"" + msg + "\"}");
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
